<template>
  <div>
    <h1>个人信息</h1>
    <div class="infoShow">
      <el-form label-width="100px" :model="userInfoForm" ref="updateFormRef" :rules="updateFormRules">
        <el-form-item label="用户名:" prop="username">
          <el-input v-model="userInfoForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话:" prop="phone">
          <el-input v-model="userInfoForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱:" prop="email">
          <el-input v-model="userInfoForm.email"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="userUpdate">修改</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UserInfo',
  data () {
    // 手机号的验证规则
    const checkPhone = (rule, value, callback) => {
      // 验证手机号的正则表达式
      const regMobile = /^([1][3,4,5,6,7,8,9])\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的手机号码'))
    }
    // 邮箱的验证规则
    const checkEmail = (rule, value, callback) => {
      // 验证邮箱的正则表达式
      const regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法的邮箱地址'))
    }
    return {
      userInfoForm: {
        uid: window.sessionStorage.getItem('uid'),
        username: window.sessionStorage.getItem('uname'),
        phone: window.sessionStorage.getItem('phone'),
        email: window.sessionStorage.getItem('email')
      },
      updateFormRules: {
        phone: [
          {
            required: true,
            message: '请输入手机号码',
            trigger: 'blur'
          },
          {
            validator: checkPhone,
            trigger: 'blur'
          }
        ],
        email: [
          {
            required: true,
            message: '请输入邮箱',
            trigger: 'blur'
          },
          {
            validator: checkEmail,
            trigger: 'blur'
          }
        ]
      }
    }
  },
  methods: {
    userUpdate () {
      this.$refs.updateFormRef.validate(async (valid) => {
        if (!valid) {
          return false
        }
        const { data: res } = await this.$axios.post('/user/update', this.userInfoForm)
        if (res.status !== 2000) {
          return this.$message.error('更新失败')
        }
        window.sessionStorage.setItem('phone', this.userInfoForm.phone)
        window.sessionStorage.setItem('email', this.userInfoForm.email)
        this.$message.success('更新成功')
        await this.$router.push('/user/info')
      })
    }
  }
}
</script>

<style scoped>
.infoShow{
  width: 1000px;
  margin-left: auto;
  margin-right: auto;
}
h1{
  text-align: center;
}
.el-button{
  width: 80px;
  margin-left: 350px;
}
</style>
